﻿namespace Mongo.Core.Repository
{
    #region

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Runtime.Serialization;
    using Interfaces;
    using Models;
    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    using MongoDB.Driver.Linq;

    #endregion

    public class UserRepository : IUserRepository
    {
        private readonly MongoCollection<User> _mongoCollection;

        public UserRepository()
        {
            MongoDatabaseInstance mongoDatabaseInstance = MongoDatabaseInstance.Instance;
            MongoDatabase mongoDatabase = mongoDatabaseInstance.MongoDatabase;
            _mongoCollection = mongoDatabase.GetCollection<User>("users");
        }

        public IQueryable<User> All
        {
            get { return _mongoCollection.AsQueryable(); }
        }

        public void Insert(User user)
        {
            _mongoCollection.Insert(user);
        }

        public void Update(User user)
        {
            _mongoCollection.Save(user);
        }

        public void Update(User user, Expression<Func<User, object>> fieldToUpdate, object newValue)
        {
            IMongoQuery selectQuery = Query<User>.EQ(u => u.Id, user.Id);
            UpdateBuilder<User> updateQuery = Update<User>.Set(fieldToUpdate, newValue);
            _mongoCollection.Update(selectQuery, updateQuery);
        }

        public void Remove(User user)
        {
            IMongoQuery selectQuery = Query<User>.EQ(u => u.Id, user.Id);
            _mongoCollection.Remove(selectQuery);
        }

        public void Remove(ObjectId objectId)
        {
            IMongoQuery selectQuery = Query<User>.EQ(u => u.Id, objectId);
            _mongoCollection.Remove(selectQuery);
        }
    }
}
